import logging

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class DouyinCollectionUpdateHistory(models.Model):
    """合集/伪合集 集数变更都会通过该模型进行记录
    * 合集的创建
    * 合集的新增（新增视频）
    * 合集的重载
    * 伪合集的创建
    * 伪合集的新增
    """
    _name = 'douyin.collection.update.history'
    _description = '合集更新记录'
    _rec_name = 'collection_id'

    alias = fields.Char(related='collection_id.alias')
    collection_id = fields.Many2one(comodel_name='douyin.collection', string='合集')
    update_time = fields.Datetime(string='更新时间', default=fields.Datetime.now)
    update_date = fields.Date(string='更新日期', compute='_compute_update_date', store=True)
    unlink_updated_videos = fields.Boolean(string='级联删除更新视频')
    video_ids = fields.One2many(
        comodel_name='douyin.video',
        inverse_name='collection_update_history_id',
        string='更新视频'
    )
    status = fields.Selection(
        string='更新状态',
        selection=[
            ('update', '更新成功'),
            ('error', '出错'),
        ]
    )
    export_discord_info = fields.Boolean(related='collection_id.export_discord_info')
    is_export_discord = fields.Boolean(string='已导出Discord信息')
    update_count = fields.Integer(string='更新集数', compute='_compute_update_count')
    note = fields.Char(string='备注')
    celery_task_id = fields.Many2one(comodel_name='celery.task', string='Celery Task')
    task_type = fields.Selection(related='celery_task_id.task_type', store=True)
    channel_name = fields.Char(related='collection_id.channel_name')

    @api.depends('update_time')
    def _compute_update_date(self):
        for rec in self:
            rec.update_date = rec.update_time

    @api.depends('video_ids')
    def _compute_update_count(self):
        for rec in self:
            rec.update_count = len(rec.video_ids)

    def action_export_discord(self):
        publish_history = self.filtered(lambda r: r.collection_id.export_discord_info)
        task_sequence = self.env['celery.task.sequence'].create({
            'sequence_type': 'publish_update',
            'task_ids': [(0, 0, {
                'task_type': 'publish_update',
                'published_history_ids': publish_history.ids
            })]
        })
        task_sequence.action_run_sequence()

    def action_export_discord_users(self):
        collection_update_map = dict(self.mapped(lambda r: (r.collection_id, r)))
        discord_users = self.env['discord.user'].search([])
        for user in discord_users:
            _logger.info(f'Discord User: {user.nickname}')
            output = []
            for fav_collection in user.favourite_collection_ids:
                history = collection_update_map.get(fav_collection)
                if history:
                    output.append(f'#{fav_collection.channel_name}，更新集数：{history.update_count}')
            content = '\r\n'.join(output)
            _logger.info(f'''
===========================
{content}
===========================
            ''')

    def unlink(self):
        unlink_videos = self.env['douyin.video'].browse()
        for rec in self:
            if rec.unlink_updated_videos:
                unlink_videos |= rec.video_ids
        unlink_videos.unlink()
        return super(DouyinCollectionUpdateHistory, self).unlink()
